<template>
	<view class="dispose-detail-page">
	  <!-- 处置信息卡片 -->
	  <view class="info-card">
		<view class="status-tag" :class="getStatusClass(disposeInfo.stateName)">
		  {{ disposeInfo.stateName }}
		</view>
		<view class="info-item">
		  <text class="label">单据编号</text>
		  <text class="value">{{ disposeInfo.code }}</text>
		</view>
		<view class="info-item">
		  <text class="label">处置资产</text>
		  <text class="value">{{ disposeInfo.assetCount }}</text>
		</view>
		<view class="info-item">
		  <text class="label">处置人</text>
		  <text class="value">{{ disposeInfo.disposePerson }}</text>
		</view>
		<view class="info-item">
		  <text class="label">处置日期</text>
		  <text class="value">{{ disposeInfo.disposeDate }}</text>
		</view>
		<view class="info-item">
		  <text class="label">处置类型</text>
		  <text class="value">{{ disposeInfo.disposeType }}</text>
		</view>
		<view class="info-item">
		  <text class="label">是否解绑标签</text>
		  <text class="value">{{ disposeInfo.isUnbindTag ? '是' : '否' }}</text>
		</view>
		<view class="info-item" v-if="disposeInfo.remark">
		  <text class="label">备注</text>
		  <text class="value">{{ disposeInfo.remark }}</text>
		</view>
	  </view>
  
	  <!-- 附件信息 -->
	  <view class="attachment-section" v-if="disposeInfo.attachments && disposeInfo.attachments.length > 0">
		<view class="section-title">附件</view>
		<view class="attachment-info">
		  <text>最多选择10个文件 大小不超过5MB格式为png/jpg/jpeg/pdf/txt/doc/xls的文件</text>
		</view>
      <!-- 已选文件展示 -->
      <view v-if="attachmentsUpload[0].files.length" class="attachment-list" >
        已上传文件：
        <view v-for="(items, index) in attachmentsUpload[0].files" :key="items.id" class="attachment-item">
          <text style="color: red" @click="handleDownFile(items)">{{ items.name }}</text>
        </view>
      </view>
	  </view>
  
	  <!-- 资产列表 -->
	  <view class="asset-section">
		<view class="section-header">
		  <text class="section-title">资产列表</text>
		  <text class="asset-count">共计: {{ disposeInfo.assets.length }}</text>
		</view>
		<view class="asset-list">
		  <view class="asset-item" v-for="(item, index) in disposeInfo.assets" :key="index">
			<view class="asset-img-container">
			  <image
			    class="asset-img"
			    :src="item.image ? `${BASE_URL}/File/GetImage?fileId=${item.image}` : '/static/placeholder.png'"
			    mode="aspectFill"
			  />
			</view>
			<view class="asset-info">
			  <view class="asset-name">{{ item.name }}</view>
			  <view class="asset-detail">资产分类: {{ item.category }}</view>
			  <view class="asset-detail">资产编码: {{ item.code }}</view>
			  <view class="asset-detail">资产规格: {{ item.spec }}</view>
			  <view class="asset-detail">资产管理人: {{ item.manager }}</view>
			  <view class="asset-detail">标签编码: {{ item.tagCode }}</view>
			</view>
		  </view>
		</view>
	  </view>
  
	  <!-- 底部按钮 -->
	  <view class="footer-btn" v-if="!isAuditMode">
		<up-button type="primary" text="返回" @click="goBack"></up-button>
	  </view>
	
	  <!-- 审核模式下的底部按钮 -->
	  <view class="footer-btn audit-btns" v-if="isAuditMode">
		<up-button type="default" text="驳回" @click="showRejectDialog"></up-button>
		<up-button type="primary" text="通过" @click="approveDisposal"></up-button>
	  </view>
	  <!-- 驳回原因弹窗 -->
	  <up-popup :show="showRejectPopup" :round="10" mode="center" @close="closeRejectDialog" @open="onRejectPopupOpen">
	    <view class="reject-popup">
	      <view class="reject-title">驳回原因</view>
	      <view class="reject-content">
	        <up-textarea
	          v-model="rejectReason"
	          placeholder="请输入驳回原因"
	          :maxlength="200"
	        ></up-textarea>
	      </view>
	      <view class="reject-buttons">
	        <up-button type="default" text="取消" @click="closeRejectDialog"></up-button>
	        <up-button type="primary" text="确定" @click="confirmReject"></up-button>
	      </view>
	    </view>
	  </up-popup>
	</view>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue';
  import { onLoad } from "@dcloudio/uni-app";
  import http,{BASE_URL} from "@/api/request";
  import { t } from "@/locale/index.js"
  
  
  // 处置信息
  const disposeInfo = ref({
	code: 'ZCCZ202504180011',
	assetCount: 11,
	disposePerson: '王森',
	disposeDate: '2025-04-18',
	disposeType: '出售',
	isUnbindTag: true,
	remark: '',
	attachments: [
	  { name: '处置文件.pdf' }
	],
	assets: [
	  {
		name: '办公家具',
		category: '办公家具',
		code: 'ZC202504030009',
		spec: '',
		manager: '王森',
		tagCode: '11',
		image: '/static/placeholder.png'
	  }
	]
  });
  
  // 页面参数
  const pageParams = ref({});
  
  // 是否是审核模式
  const isAuditMode = ref(false);
  
  // 驳回原因
  const rejectReason = ref('');

  const attachmentsUpload = ref([
  {
    Fileld: [],
    files: [],
    linkId: "1",
    taskId: "<%assetdisposalmstr.id%>",
  },
]);
  
  // 使用onMounted替代onLoad
  onLoad((options) => {
	pageParams.value = options;
	// 检查是否是审核模式
	if (options.mode === 'audit') {
	  isAuditMode.value = true;
	}
  if(isAuditMode.value){
    uni.setNavigationBarTitle({
      title: t('assetsDisposal.audit'),
    });
  }
  else{
    uni.setNavigationBarTitle({
      title: t('assetsDisposal.detail'),
    });
  }
	
	// 如果有传入disposalCode，则根据disposalCode获取处置详情
	if (options.disposalCode) {
	  getDisposeDetail(options.disposalCode).then(() => {
      if (disposeInfo.value.id) {
        getFiles();
      }
    });
	}
  });


  // 获取已有附件
const getFiles = async () => {
  const postData = {
    linkId: "1",
    taskId: disposeInfo.value.id,
  };
  console.log(postData);
  const { code, isSuccess, result } = await http.post(
    "/api/file/GetTaskLinkedFiles",
    postData
  );
  if (code && isSuccess && result) {
    result.forEach((item) => {
      attachmentsUpload.value[0].files.push({
        id: item.id,
        name: item.fileName + "  " + item.userName + "  " + item.creationTime,
        url: `/File/Download?fileId=` + item.id,
      });
    });
  }
};

// 添加文件下载方法
const handleDownFile = (items) => {
  uni.downloadFile({
    url: BASE_URL + items.url,
    success: (res) => {
      if (res.statusCode === 200) {
        plus.runtime.openFile(res.tempFilePath, {}, (e) => {
          uni.showModal({
            title: "无法打开文件",
            content: "请安装 WPS Office 或 QQ 浏览器等可打开该文件的应用",
            confirmText: "去安装",
            success: (modalRes) => {
              if (modalRes.confirm) {
                try {
                	plus.runtime.openURL('market://details?id=com.tencent.mtt', () => {
                		plus.runtime.openURL('https://browser.qq.com');
                	});
                } catch (e) {
                	plus.runtime.openURL('https://browser.qq.com');
                }
              }
            },
          });
        });
      }
    },
    fail: (err) => {
      console.error("下载失败", err);
      uni.showToast({ title: "下载失败", icon: "none" });
    },
  });
};
  
  // 获取处置详情
  const getDisposeDetail = (disposalCode) => {
    // 显示加载中
    uni.showLoading({
      title: '加载中...'
    });
    
    // 构建请求参数
    const data = { 
      "pageCode": "assetdisposal", 
      "params": { 
        "args": [ 
          { 
            "name": "interfaceCode", 
            "value": "assetdisposal.getAssetDisposalOrderDetails" 
          }, 
          { 
            "name": "disposalCode", 
            "value": disposalCode 
          } 
        ] 
      }, 
      "methodName": "getAssetDisposalOrderDetails" 
    };
    
    // 调用接口
    return http.post("/api/module/Invoke", data).then((res) => {
      uni.hideLoading();
      
      if (res.isSuccess && res.result) {
        // 获取主单据信息和资产列表
        const mstr = res.result.assetDisposalMstr || {};
        const assetList = res.result.assetDetVOs || [];
        
        // 更新处置信息
        // 更新处置信息
        disposeInfo.value = {
          id: mstr.id,
          code: mstr.disposalCode || disposalCode,  // 修改这里，将 id 改为 disposalCode
          assetCount: assetList.length,
          disposePerson: mstr.disposalUserName || '',
          disposeDate: mstr.disposalDate || '',
          disposeType: mstr.disposalTypeName || '',
          isUnbindTag: mstr.isUnbindTag === 'YES',
          remark: mstr.remark || '',
          stateName: mstr.stateName || '未知状态', // 添加状态名称
          // 附件处理，如果有附件ID，可以在这里处理
          attachments: mstr.attachment ? [{ name: '附件文件', id: mstr.attachment }] : [],
          // 处理资产列表
          assets: assetList.map(asset => ({
            id: asset.id,
            name: asset.assetName,
            category: asset.assetClassName,
            code: asset.assetCode,
            spec: asset.specModel,
            manager: asset.assetAdminName || '未分配',
            tagCode: asset.labelNumber,
            image: asset.image ? asset.image.trim() : '/static/placeholder.png'
          }))
        };
        return res.result;
      } else {
        uni.showToast({
          title: res.error || '获取详情失败',
          icon: 'none'
        });
        throw new Error(res.error || '获取详情失败');
      }
    }).catch(err => {
      uni.hideLoading();
      console.error('获取处置详情失败:', err);
      uni.showToast({
        title: '网络异常，请稍后重试',
        icon: 'none'
      });
      throw err;
    });
  };
  
  // 返回上一页
  const goBack = () => {
	uni.navigateBack();
  };

  // 驳回弹窗显示状态
  const showRejectPopup = ref(false);
  
  // 显示驳回原因弹窗
  const showRejectDialog = () => {
  rejectReason.value = '';
  showRejectPopup.value = true;
  };
  
  // 关闭驳回原因弹窗
  const closeRejectDialog = () => {
  showRejectPopup.value = false;
  };
  
  // 弹窗打开事件
  const onRejectPopupOpen = () => {
  console.log('驳回弹窗已打开');
  };
  
  // 确认驳回
  const confirmReject = () => {
  if (!rejectReason.value.trim()) {
    uni.showToast({
      title: '请输入驳回原因',
      icon: 'none'
    });
    return;
  }
  rejectDisposal();
  closeRejectDialog();
  };

  // 审核通过
  const approveDisposal = () => {
    uni.showModal({
      title: '审核确认',
      content: `确定通过处置单 ${pageParams.value.disposalCode} 的审核吗？`,
      cancelText: '取消',
      confirmText: '确定',
      success: (res) => {
        if (res.confirm) {
          // 调用审核通过接口
          submitAudit('APPROVED');
        }
      }
    });
  };

  // 驳回处置单
  const rejectDisposal = () => {
    // 调用驳回接口
    submitAudit('REJECTED');
  };

  // 提交审核结果
  const submitAudit = (auditResult) => {
    uni.showLoading({
      title: '提交中...'
    });
    
    const data = { 
      pageCode: "assetdisposal", 
      params: { 
        args: [ 
          { 
            name: "interfaceCode", 
            value: "assetdisposal.auditAssetDisposalOrder" 
          }, 
          { 
            name: "disposalCode", 
            value: pageParams.value.disposalCode
          },
          {
            name: "auditState",
            value: auditResult
          },
          {
            name: "approvalReason",
            value: auditResult === 'REJECTED' ? rejectReason.value : ''
          }
        ] 
      }, 
      methodName: "auditAssetDisposalOrder" 
    };
    
    http.post("/api/module/Invoke", data).then((res) => {
      uni.hideLoading();
      if (res.isSuccess) {
        uni.showToast({
          title: auditResult === 'APPROVED' ? '审核通过成功' : '驳回成功',
          icon: 'success'
        });
        
        // 触发列表页面数据刷新
        uni.$emit('disposalDataChanged');
        
        // 延迟返回，确保提示信息显示完成
        setTimeout(() => {
		uni.navigateBack();
        }, 1500);
      } else {
        uni.showToast({
          title: res.error || '操作失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      uni.hideLoading();
      console.error('审核操作失败:', err);
      uni.showToast({
        title: '网络异常，请稍后重试',
        icon: 'none'
      });
    });
  };
    
  // 根据状态名称返回对应的样式类
  const getStatusClass = (stateName) => {
  if (!stateName) return '';
  if (stateName.includes('完成')) return 'status-completed';
  if (stateName.includes('待')) return 'status-pending';
  if (stateName.includes('拒绝')) return 'status-rejected';
  return '';
  };
  </script>
  
  <style lang="scss" scoped>

  .dispose-detail-page {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 120rpx;
  }
  
  .info-card {
	background-color: #fff;
	margin: 20rpx;
	padding: 30rpx;
	border-radius: 12rpx;
	position: relative;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  }
  
  .status-tag {
	position: absolute;
	top: 30rpx;
	right: 30rpx;
	font-size: 28rpx;
  }
  
  .info-item {
	display: flex;
	margin-bottom: 20rpx;
	font-size: 28rpx;
	line-height: 1.5;
  }
  
  .label {
	color: #666;
	width: 180rpx;
  }
  
  .value {
	flex: 1;
	color: #333;
  }
  
  .section-title {
	font-size: 32rpx;
	font-weight: bold;
	margin: 30rpx 20rpx 20rpx;
  }
  
  .attachment-section {
	background-color: #fff;
	margin: 20rpx;
	padding: 20rpx 30rpx 30rpx;
	border-radius: 12rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  }
  
  .attachment-info {
	font-size: 24rpx;
	color: #999;
	margin-bottom: 20rpx;
  }
  
  .attachment-list {
	display: flex;
	flex-direction: column;
  }
  
  .attachment-item {
	padding: 20rpx 0;
	border-bottom: 1rpx solid #eee;
	font-size: 28rpx;
  }
  
  .asset-section {
	background-color: #fff;
	margin: 20rpx;
	padding: 20rpx 30rpx 30rpx;
	border-radius: 12rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  }
  
  .asset-count {
	font-size: 26rpx;
	color: #666;
	margin-bottom: 20rpx;
  }
  
  .asset-list {
	display: flex;
	flex-direction: column;
  }
  
  .asset-item {
	display: flex;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #eee;
  }
  
  .asset-img-container {
	width: 120rpx;
	height: 120rpx;
	margin-right: 20rpx;
  }
  
  .asset-img {
	width: 100%;
	height: 100%;
	border-radius: 8rpx;
	background-color: #f0f0f0;
  }
  
  .asset-info {
	flex: 1;
  }
  
  .asset-name {
	font-size: 30rpx;
	font-weight: bold;
	margin-bottom: 10rpx;
  }
  
  .asset-detail {
	font-size: 26rpx;
	color: #666;
	margin-bottom: 6rpx;
  }
  
  .footer-btn {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 20rpx 30rpx;
	background-color: #fff;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  }
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20rpx 20rpx;
  }
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
  }
  
  .asset-count {
    font-size: 26rpx;
    color: #666;
  }
  .status-pending {
    color: #f0ad4e; /* 黄色 - 待处理 */
  }
  
  .status-completed {
    color: #4cd964; /* 绿色 - 已完成 */
  }
  
  .status-rejected {
    color: #dd524d; /* 红色 - 已拒绝 */
  }
  .audit-btns {
  display: flex;
  justify-content: space-between;
}

.audit-btns button {
  width: 45%;
}
.reject-popup {
  background-color: #fff;
  border-radius: 12rpx;
  width: 600rpx;
  padding: 30rpx;
}

.reject-title {
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
}

.reject-content {
  margin-bottom: 30rpx;
}

.reject-buttons {
  display: flex;
  justify-content: space-between;
}

.reject-buttons button {
  width: 45%;
}
  </style>


  
